<template>
  <div class="import-task-drawer drawerWrap mx5">
    <div>
      <el-form :model="formOption.data" ref="formRef" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="数据源名称" prop="name">
              <ns-input placeholder="请输入数据源名称" v-model="formOption.data.name" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资产IP" prop="ip">
              <ns-input placeholder="请输入资产IP" v-model="formOption.data.ip" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资产类型" prop="assetType">
              <el-select
                placeholder="请选择资产类型"
                v-model="formOption.data.assetType"
                filterable
                clearable
              >
                <el-option
                  v-for="item in formOption.assetTypeList"
                  :key="item.name"
                  :label="item.showName"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归属系统" prop="sysId">
              <el-cascader
                v-model="formOption.data.sysId"
                placeholder="请选择归属系统"
                :props="formOption.systemCascaderProps"
                :options="formOption.systemList"
                filterable
                clearable
                :filter-method="sysFilterMethod"
                disabled
                value-on-clear=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归属机构" prop="deptId">
              <el-cascader
                v-model="formOption.data.deptId"
                placeholder="请选择归属机构"
                :props="formOption.cascaderProps"
                value-on-clear="0"
                :options="formOption.deptList"
                filterable
                clearable
                :filter-method="sysFilterMethod"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="text-right">
            <el-button type="primary" @click="query">搜索</el-button>
            <el-button @click="resetSearch"> 重置 </el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-divider />
      <AsyncTable
        v-bind="secondColums"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="handleSelectionChange"
      />
    </div>
    <div class="">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import { ElMessageBox, ElMessage, ElRadioGroup, ElRadio, ElAlert } from 'element-plus'
import { onMounted, ref } from 'vue'
import cloneDeep from 'lodash-es/cloneDeep'
import * as api from '@/api/asset/taskManage'
import { getDataSourceList } from '@/api/dataSourceManage/index'
import { getAssetTypeList } from '@/api/dataSourceManage/index'
import { handleTree } from '@/utils/tree'
import { getSimpleDeptList } from '@/api/system/dept'
import { sysFilterMethod } from '@/utils/selectFilter'
import { Hide, View } from '@element-plus/icons-vue'
const formRef = ref()
const tableRef = ref()

const emit = defineEmits(['update:model-value'])
const props = defineProps(['params', 'closeOutDrawer'])
const allSelect = ref(false)

const formOption = reactive({
  data: {
    name: '',
    ip: '',
    assetType: '',
    deptId: '',
    sysId: ''
  },
  assetTypeList: [],
  systemList: [],
  deptList: [],
  cascaderProps: {
    checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'children',
    emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
  },
  systemCascaderProps: {
    checkStrictly: true,
    label: 'value',
    value: 'id',
    children: 'children',
    emitPath: false
  }
})

const columns = computed(() => {
  const baseColumns = [
    {
      type: 'selection',
      width: 40,
      selectable: (row) => {
        return row.statusName === '已完成' || row.statusName === '已停止'
      }
    },
    {
      label: '任务名称',
      render: ({ row }) => (
        <div class="flex items-center">
          <el-icon class="mr-5" color="red">
            <WarningFilled />
          </el-icon>
          <div>{row.name}</div>
        </div>
      )
    },
    { prop: 'typeName', label: '任务类型', 'show-overflow-tooltip': true },
    {
      label: '执行进度',
      render: ({ row }) => <el-progress percentage={row.progress.replace('%', '')} />
    },
    {
      prop: 'statusName',
      label: '状态',
      width: 80,
      'show-overflow-tooltip': true
    },
    { prop: 'scanTime', label: '扫描时间', 'show-overflow-tooltip': true }
  ]
  return baseColumns
})
const handleShowIp = (row) => {
  row.isShowIp = !row?.isShowIp
}
const secondColums = computed(() => {
  return {
    columns: [
      {
        type: 'selection',
        width: '40px'
      },
      {
        label: '数据源名称',
        prop: 'name'
      },
      {
        label: '资产IP:端口',
        width: 170,
        render: ({ row }) => {
          return (
            <>
              <div style="display:flex;align-items:center;justify-content:space-between;">
                {row?.isShowIp ? (
                  <span>{row.port ? row.ip + ':' + row.port : row.ip}</span>
                ) : (
                  <span style="font-size:17px">***********</span>
                )}
                {row?.isShowIp ? (
                  <el-icon>
                    <Hide onClick={() => handleShowIp(row)} />
                  </el-icon>
                ) : (
                  <el-icon>
                    <View onClick={() => handleShowIp(row)} />
                  </el-icon>
                )}
              </div>
            </>
          )
        }
      },
      {
        label: '资产类型',
        render({ row }) {
          return (
            <>
              <span>{row.assetTypeName || row.assetType}</span>
            </>
          )
        }
      },
      {
        label: '库名',
        prop: 'dbName',
        hide: props.params.datasourceType == 2
      },
      {
        label: '归属机构',
        prop: 'department'
      },
      {
        label: '归属系统',
        prop: 'system'
      },
      {
        label: '最近扫描时间',
        prop: 'scanTime'
      },
      {
        label: '连接信息',
        prop: 'configStatus',
        minWidth: 150,
        align: 'center',
        render: (cellData) => (
          <span class={cellData === 1 ? 'text-success' : 'text-info'}>
            {cellData === 1 ? '已配置' : '未配置'}
          </span>
        )
      }
    ],
    data: []
  }
})

async function allSelectHandle() {
  allSelect.value = !allSelect.value
  tableRef.value.ignorePageSelect(allSelect.value)
}

async function fetchData({ page, pageSize }) {
  formOption.data.sysId = props.params.sysId
  formOption.data.deptId = props.params.deptId
  const res = await getDataSourceList({
    ...formOption.data,
    datasourceType: props.params.datasourceType,
    configStatus: 1,
    page,
    pageSize
  })
  return {
    data: res.data,
    count: res.count
  }
}

const taskData = reactive({
  selectedRows: []
})

function handleSelectionChange(rows) {
  taskData.selectedRows = rows
}

function cancel() {
  props.closeOutDrawer()
}

async function handleSubmit() {
  if (allSelect.value) {
    const res = await getDataSourceList({
      ...formOption.data,
      datasourceType: props.params.datasourceType,
      configStatus: 1,
      page: 1,
      pageSize: 99999
    })
    console.log(res.data)
    props.params?.callBack(res.data)
  } else {
    props.params?.callBack(taskData.selectedRows)
  }
  props.closeOutDrawer()
}

function resetSearch() {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

const query = () => {
  tableRef.value.fetchData()
}

async function getDeptList() {
  const data = await getSimpleDeptList()
  formOption.deptList = data
}

async function getSystemList() {
  const data = await api.getSimpleSystemList()
  formOption.systemList = handleTree(data, 'id', 'pid')
}

async function getAssetTypeEnum() {
  const data = await getAssetTypeList()
  formOption.assetTypeList = data
}

onMounted(() => {
  getDeptList()
  getSystemList()
  getAssetTypeEnum()
})
</script>
<style lang="scss" scoped>
.import-task-drawer {
  .ns-input,
  .el-select {
    width: 100%;
  }
  :deep(.el-cascader) {
    width: 100%;
  }
  :deep(.text-info) {
    color: #409eff;
  }
  :deep(.text-success) {
    color: #67c23a;
  }
}
</style>
